<template>
  <div>
    <!-- 卡片视图 -->
    <el-card>
      <!--  Alert 组件 -->
      <el-alert
        title="添加商品信息"
        type="info"
        centerm
        show-icon
        :closable="false"
      ></el-alert>
      <!-- 步骤条 -->
      <el-steps
        :space="300"
        :active="parseInt(activeIndex)"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <!-- <el-step title="商品属性"></el-step> -->
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- Tab标签 -->

      <el-form
        :model="addForm"
        ref="addFormRef"
        :rules="addFormRules"
        label-width="100px"
        label-position="top"
      >
        <!-- :rules="addFormRules" -->
        <el-tabs
          tab-position="left"
          v-model="activeIndex"
          :before-leave="beforeTabsLeave"
          @tab-click="tabClicked"
          style="margin-top: 20px; margin-left: 20px"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="CommodityName">
              <el-select
                v-model="addForm.CommodityName"
                placeholder="请选择商品名称"
              >
                <el-option
                  v-for="item in commSpulist"
                  :key="item.id"
                  :label="item.commodityName"
                  :value="item.commodityName"
                  style="margin-bottom: 5px"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="商品价格" prop="Price">
              <el-input-number
                v-model="addForm.Price"
                @change="handleChange"
                :min="1"
                label="描述文字"
              ></el-input-number>
            </el-form-item>

            <el-form-item label="商品数量" prop="Inventory">
              <el-input-number
                v-model="addForm.Inventory"
                @change="handleChange"
                :min="1"
                label="描述文字"
              ></el-input-number>
            </el-form-item>
          </el-tab-pane>

          <!-- 、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、 -->
          <el-tab-pane label="商品参数" name="1">
            商品参数

            <!-- 商品参数 -->
            <div>
              <div>SKU组合demo</div>
              <div v-for="(v, i) in dataTableSpe" :key="i" class="mt-20">
                <b>{{ v.specificationName }}：</b>
                <el-checkbox-group v-model="checkList[i].lib" :max="1">
                  <el-checkbox
                    v-for="(k, j) in v.lib"
                    :key="j"
                    :label="k.spchildrenName"
                  />
                </el-checkbox-group>
              </div>
              <div class="mt-20">
                <el-button type="primary" @click="handleClick">确定</el-button>
              </div>
              <div class="mt-20">
                <el-tag
                  v-for="(item, index) in skuList"
                  :key="index"
                  style="margin: 10px 10px"
                  >{{ item }}</el-tag
                >
              </div>
            </div>
          </el-tab-pane>

          <!-- 、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、 -->

          <el-tab-pane label="商品图片" name="3">
            <el-button
              icon="el-icon-document-add"
              type="primary"
              @click="handlPicture"
              >点击上传</el-button
            >

            <!-- 商品图片表 -->
            <el-table
              :data="pictureData"
              style="width: 100%"
              :header-cell-style="{ textAlign: 'center' }"
              :cell-style="{ textAlign: 'center' }"
            >
              <el-table-column label="图片">
                <template slot-scope="scope">
                  <img :src="localhostPath + scope.row.commodityPicturePath" />
                </template>
              </el-table-column>

              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-popconfirm
                    title="确定删除吗？"
                    @confirm="handleDelete(scope.$index, scope.row)"
                  >
                    <el-button size="mini" type="danger" slot="reference"
                      >删除</el-button
                    >
                  </el-popconfirm>
                </template>
              </el-table-column>
            </el-table>

            <!-- 添加图片框 -->
            <el-dialog
              title="添加图片"
              :visible.sync="dialogFormVisible"
              width="500px"
            >
              <el-form ref="form" :model="form">
                <el-form-item label="图片" :label-width="formLabelWidth">
                  <el-upload
                    :class="{ hide: hideUpload }"
                    ref="upload"
                    action="#"
                    accept="image/png,image/gif,image/jpg,image/jpeg"
                    list-type="picture-card"
                    :limit="1"
                    :auto-upload="false"
                    :before-upload="handleBeforeUpload"
                    :on-change="handleChanges"
                    :on-remove="handleRemoves"
                    :file-list="listarr"
                  >
                    <i class="el-icon-plus"></i>
                  </el-upload>

                  <my-cropper
                    ref="myCropper"
                    @getFile="getFile"
                    @upAgain="upAgain"
                  ></my-cropper>
                </el-form-item>
              </el-form>

              <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="confirm('form')"
                  >确 定</el-button
                >
              </div>
            </el-dialog>
            <!-- <el-upload
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headerObj"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload> -->
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- markdown -->
            <div>
              <mavon-editor
                :ishljs="true"
                ref="md"
                @imgAdd="imgAdd"
                @imgDel="imgDel"
                style="height: 100vh"
                v-model="formsa.mdContent"
                @change="change"
                >123</mavon-editor
              >
            </div>
            <el-button type="primary" class="btn" @click="addProducts"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
  </div>
</template>
<script>
// import _ from "lodash";
import { getSpe, getSpechild } from "../../api/spe";
import {
  addComm,
  addCommPicture,
  deleteCommPicture,
  gteCommspu,
  addPicture,
  deletePicture,
  addCommCont,
} from "../../api/comm";
import common from "../../utils/common";
import MyCropper from "../../components/cropper.vue";

export default {
  components: { MyCropper },
  data() {
    return {
      localhostPath: common.localhostPath,
      //图片数组
      pictureData: [],
      tableData: [],

      // 当上传一张图片后隐藏上传框
      hideUpload: false,
      formLabelWidth: "100px",
      dialogFormVisible: false,
      list: [
        { name: "尺码", list: ["S", "M", "L", "XL", "XXL"] },
        { name: "颜色", list: ["红色", "黄色", "蓝色", "粉色", "紫色"] },
        { name: "图案", list: ["猫咪", "人物", "飞机", "闪电", "字母"] },
      ],
      checkList: [],
      skuArray: [],
      skuList: [],
      listarr: [],
      //存放SPU数组
      commSpulist: [],
      commId: 0,
      commskuId: 0,

      form: {
        id: 0,
      },

      //
      formsa: {
        articleContent: "", // 转成的html
        mdContent: "", // 输入的markdown
      },
      selectedKeys: {},
      // commSpuId:0,
      activeIndex: "0",
      addForm: {
        CommodityName: "",
        // CommodityExplain: "",
        Price: "",
        Inventory: "",
        // 商品所属的分类ID
        // CommodityClassificationId: 1,
        UserId: 5,
        //参数（子类）Id串
        SpeChildId: "",
      },
      addFormRules: {
        CommodityName: [
          { required: true, message: "请输入商品名称", trigger: "black" },
        ],
        Price: [{ required: true, message: "请输入商品价格", trigger: "blur" }],
        CommodityExplain: [
          { required: true, message: "请输入商品描述", trigger: "blur" },
        ],
        Inventory: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
        ],
      },
      pics: [],
      goods_introduce: "",
      attrs: [],
      //商品分类存放数组
      cateList: [],
      selectedCateId: [],
      catProps: {
        value: "id",
        label: "classificationName",
        children: "children",
        checkStrictly: true,
      },
      manyDataList: [],
      dataTableSpe: [],
      picForm: {
        picPath: "",
      },
      img_file: [],
    };
  },
  //在实例创建完成后被立即调用。
  created() {
    this.getCatList();
  },
  mounted() {
    // //分类
    // getType().then(({ data }) => {
    //   this.cateList = data.data;
    //   console.log(data.data);
    // });
    setTimeout(() => {
      this.getAllSpeChild();
    }, 200);
    this.getAllSpe();
    this.AllcommSpu();
  },
  methods: {
    imgDel(pos) {
      delete this.img_file[pos];
      let str = pos[0];
      this.picForm.picPath = "/" + str.split("/")[3] + "/" + str.split("/")[4];
      deletePicture(this.picForm).then((data) => {
        console.log(data);
      });
    },
    // 将图片上传到服务器，返回地址替换到md中
    // 绑定@imgAdd event
    imgAdd(pos, $file) {
      // 第一步.将图片上传到服务器.
      var formdata = new FormData();
      formdata.append("images", $file);
      addPicture(formdata).then((data) => {
        // 第二步.将返回的url替换到文本原位置![...](0) -> ![...](url)
        // $vm.$img2Url 详情见本页末尾
        var url = this.localhostPath + data.data.data;
        this.$refs.md.$img2Url(pos, url);
      });
    },
    //所有商品spu
    AllcommSpu() {
      var spuId = this.addForm.UserId;
      gteCommspu(spuId)
        .then(({ data }) => {
          this.commSpulist = data.data;
          console.log(data);
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //图片删除
    handleDelete(index, row) {
      console.log(index, row.id);
      deleteCommPicture(row.id)
        .then(({ data }) => {
          console.log(data);
        })
        .catch((err) => {
          console.log(err);
        });
      this.pictureData.splice(index, 1);
    },

    //确定按钮提交数据（商品SPU及商品SKU）
    handleClick() {
      // 先清空数据，保证连续点击按钮，数据不会重复
      this.skuArray = [];
      this.skuList = [];
      // 将选中的规格组合成一个大数组 [[1, 2], [a, b]...]
      console.log(this.checkList);
      console.log(this.dataTableSpe);

      this.checkList.forEach((element) => {
        element.lib.length > 0 ? this.skuArray.push(element.lib) : "";
      });
      console.log(this.skuArray);
      // 勾选了规格，才调用方法
      if (this.skuArray.length > 0) {
        this.getSkuData([], 0, this.skuArray);

        //字符串转数组和数组转字符串
        console.log(this.skuList);
        let obj = {
          speStringId: this.skuList.toString(),
        };

        this.addForm.SpeChildId = this.skuList.toString();
        console.log(this.addForm);
        if (this.addForm.CommodityName == "") {
          this.$message({
            showClose: true,
            message: "商品名称不能为空!",
            type: "error",
          });
        } else if (this.addForm.Inventory == "" || this.addForm.Price == "") {
          this.$message({
            showClose: true,
            message: "请填写完整!",
            type: "error",
          });
        }
        //添加详情
        addComm(this.addForm)
          .then(({ data }) => {
            console.log(data);
            this.commId = data.data.commodityId;
            this.commskuId = data.data.id;
            console.log(this.commId);
          })
          .catch((err) => {
            console.log(err);
          });

        console.log(obj);
        console.log(obj.speStringId.split(","));
      } else {
        this.$message.error("请先勾选规格");
      }
    },
    // 递归获取每条SKU数据
    getSkuData(skuArr = [], i, list) {
      for (let j = 0; j < list[i].length; j++) {
        if (i < list.length - 1) {
          skuArr[i] = list[i][j];
          this.getSkuData(skuArr, i + 1, list); // 递归循环
        } else {
          this.skuList.push([...skuArr, list[i][j]]); // 扩展运算符，连接两个数组
        }
      }
    },
    //点击添加按钮
    handlPicture() {
      this.dialogFormVisible = true;
      this.form = {};
      this.listarr = [];
      this.hideUpload = false;
    },

    //查找父类参数
    getAllSpe() {
      getSpe()
        .then(({ data }) => {
          console.log(data);
          let arr = [];
          let other = [];
          data.data.forEach((item) => {
            let obj = {
              id: item.id,
              specificationName: item.specificationName,
              lib: [],
            };
            arr.push(obj);
            let otherobj = {
              id: item.id,
              specificationName: item.specificationName,
              lib: [],
            };
            other.push(otherobj);
          });
          this.dataTableSpe = arr;
          this.checkList = other;
          console.log(this.dataTableSpe);
          console.log(this.checkList);
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //查找子级参数
    getAllSpeChild() {
      getSpechild()
        .then(({ data }) => {
          this.dataTableSpe.forEach((Element) => {
            let newArr = [];
            console.log(data.data);
            data.data.forEach((item) => {
              if (item.specificationId == Element.id) {
                newArr.push(item);
              }
            });
            Element.lib = newArr;
            console.log(this.dataTableSpe);
          });
          console.log(data.data);
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 点击弹框重新时触发
    upAgain() {
      this.$refs["upload"].$refs["upload-inner"].handleClick();
    },
    // 获取裁剪后的图片
    getFile(file) {
      this.$nextTick(() => {
        this.$refs.myCropper.close();
      });
      var url = window.URL.createObjectURL(file);
      this.listarr.push({ name: file.name, url: url, file: file });
    },
    //确定上传支付信息(支付方式和图片)
    confirm(formName) {
      // 添加
      this.$refs[formName].validate((valid) => {
        console.log(valid);
        if (valid) {
          var commdyId = this.commId;
          if (this.listarr.length == 0) {
            this.$message.error("图片不为空");
          } else {
            const fileObj = this.listarr[0].file;
            const form1 = new FormData();
            form1.append("imageFile", fileObj);

            addCommPicture(commdyId, form1)
              .then(({ data }) => {
                console.log(data);
                if (data.data == "") {
                  this.$message.error("数据未完善无法上传图片");
                } else {
                  this.pictureData.push(data.data);
                }
                // if (data.code == 200) {
                //   this.tableData.push(data.data);
                this.dialogFormVisible = false;
                //   this.$refs.upload.clearFiles();
                // } else {
                //   this.$message.error(data.msg);
                // }
              })
              .catch((err) => {
                console.log(err);
              });
          }
        } else {
          this.$message.error("该空不能为空，请填写完毕重新提交");
        }
      });
    },
    ////////////////////////////////////////////////////////////////////

    handleRemoves() {
      this.hideUpload = false;
    },
    handleBeforeUpload(file) {
      console.log("before");
      if (
        !(
          file.type === "image/png" ||
          file.type === "image/gif" ||
          file.type === "image/jpg" ||
          file.type === "image/jpeg"
        )
      ) {
        this.$notify.warning({
          title: "警告",
          message:
            "请上传格式为image/png, image/gif, image/jpg, image/jpeg的图片",
        });
      }
      let size = file.size / 1024 / 1024 / 2;
      if (size > 2) {
        this.$notify.warning({
          title: "警告",
          message: "图片大小必须小于2M",
        });
      }
    },
    handleChanges(file, fileList) {
      this.hideUpload = true;
      this.dialogImageUrl = file.url;
      if (fileList.length > 0) {
        this.photoList = [fileList[fileList.length - 1]];
      }
      this.handleCrop(file);
    },
    //上传图片触发
    handleCrop(file) {
      this.$nextTick(() => {
        this.$refs.myCropper.open(file.raw || file, 100, 100, 1, 1);
      });
    },
    ////////////////////////////////////////////////////////////////////

    getCatList() {
      //   const { data: res } = await this.$http.get('categories')
      //   if (res.meta.status !== 200) {
      //     return this.$message.error('获取分类列表失败')
      //   }
      //   this.cateList = res.data
      // console.log(this.cateList)
    },
    // 级联选择器选中项变化，会触发这个函数
    handleChange(values) {
      console.log(values);
      console.log(values[values.length - 1]);
      var end = values[values.length - 1];
      this.addForm.CommodityClassificationId = end;
      console.log(this.addForm.CommodityClassificationId);
    },
    // 阻止Tab切换
    beforeTabsLeave(activeName, oldActiveName) {
      console.log(activeName, oldActiveName);
      console.log("目前的标签名称" + activeName);
      console.log("离开的标签名称" + oldActiveName);
      //   if (oldActiveName === '0' ) {
      //     this.$message.error('请先选择商品分类')
      //     return false
      // }
    },
    // Tab点击事件
    async tabClicked() {
      // console.log(this.activeIndex)
      //   if (this.activeIndex === '1') {
      //     // console.log('动态参数面板')
      //     // 发送参数，选中many表示动态参数
      //     const {
      //       data: res
      //     } = await this.$http.get(`categories/${this.cateId}/attributes`, {
      //       params: { sel: 'many' }
      //     })
      //     // console.log(res)
      //     if (res.meta.status !== 200) {
      //       return this.$message.error('数据获取失败')
      //     }
      //     res.data.forEach(item => {
      //       item.attr_vals =
      //         item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
      //     })
      //     this.manyDataList = res.data
      //     // console.log(res.data)
      //   } else if (this.activeIndex === '2') {
      //     const {
      //       data: res
      //     } = await this.$http.get(`categories/${this.cateId}/attributes`, {
      //       params: { sel: 'only' }
      //     })
      //     // console.log(res)
      //     if (res.meta.status !== 200) {
      //       return this.$message.error('数据获取失败')
      //     }
      //     this.onlyTableData = res.data
      //   }
    },
    handleSuccess(response) {
      // console.log(response)
      //  拼接得到一个图片信息对象
      const objInfo = { pic: response.data.tmp_path };
      //  将图片信息对象 push到pics数组中
      this.addForm.pics.push(objInfo);
      // console.log(this.addForm)
    },
    handlePreview() {},
    handleRemove(file) {
      // console.log(file)
      // 获取将要删除图片的临时路径
      const filePath = file.response.data.tmp_path;
      // console.log(filePath)
      // 从pics数组中，找到这个图片对应的索引值,x为循环数组每一项得到的数据
      // findIndex和find差不多，不过默认返回的是索引，如果没有符合条件的元素返回 -1
      const i = this.addForm.pics.findIndex((x) => x.pic === filePath);
      // 调用数组的splice方法，把图片信息对象，从pics数组中删除
      this.addForm.pics.splice(i, 1);
      // splice() 方法向/从数组中添加/删除项目，然后返回被删除的项目（两个参数必需。整数，规定添加/删除项目的位置，使用负数可从数组结尾处规定位置。，要删除的项目数量
      console.log(this.addForm);
    },
    // 添加商品按钮
    addProducts() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) {
          console.log("s");
          console.log(this.formsa);
          return this.$message.error("请填写表单必填项!");
        } else {
          var skuid = this.commskuId;
          console.log(skuid);
          if (skuid == 0) {
            this.$message({
              showClose: true,
              message: "请填写商品名称!",
              type: "error",
            });
          } else {
            if (this.formsa.mdContent == "") {
              this.$message({
                showClose: true,
                message: "内容为空，请填写内容!",
                type: "error",
              });
            } else {
              addCommCont(skuid, this.formsa)
                .then(({ data }) => {
                  if (data.data != "") {
                    this.$message({
                      showClose: true,
                      message: "添加成功",
                      type: "success",
                    });
                    this.$router.push(
                      "/Store/StoreManagement/StoreCommodityManagement"
                    );
                  } else {
                    this.$message({
                      showClose: true,
                      message: "添加失败",
                      type: "error",
                    });
                  }

                  console.log(data);
                })
                .catch((err) => {
                  console.log(err);
                });
            }
          }

          // console.log("s");

          // var skuId=this.commskuId;
        }
        //  执行添加的业务逻辑
        //  goods_cat是字符串，所以把数组转换成字符串
        // 使用lodash中的深拷贝方法
        // const form = _.cloneDeep(this.addForm);
        // form.goods_cat = form.goods_cat.join(",");
        // this.manyDataList.forEach((item) => {
        //   const newInfo = {
        //     attr_id: item.attr_id,
        //     attr_value: item.attr_vals.join(" "),
        //     // join数组转字符串，空格做分隔
        //   };
        //   this.addForm.attrs.push(newInfo);
        // });
        // // forEach()：对数组进行遍历循环，这个方法没有返回值
        // this.onlyTableData.forEach((item) => {
        //   const newInfo = {
        //     attr_id: item.attr_id,
        //     attr_value: item.attr_vals,
        //   };
        //   this.addForm.attrs.push(newInfo);
        //   // push()：方法可向数组的末尾添加一个或多个元素，并返回新的长度
        // });
        // form.attrs = this.addForm.attrs;
        // // console.log(form)
        // // 发起请求，添加商品，商品名称必须是唯一的
        // const { data: res } = await this.$http.post("goods", form);
        // if (res.meta.status !== 201) {
        //   return this.$message.error("添加商品失败");
        // }
        // this.$message.success("添加商品成功");
        // this.$router.push("/goods");
      });
    },

    change(value, render) {
      //实时获取转成html的数据
      this.form.articleContent = render;
      this.form.mdContent = value;
    },
  },
  computed: {
    // 获取三级的id
    cateId() {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2];
      }
      return null;
    },
  },
};
</script>
<style>
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.btn {
  margin-top: 15px;
}
.hide .el-upload--picture-card {
  display: none;
}
</style>
